<template>
  <div class="main">
    <main class="sign-main">
      <div class="image-box">
        <img :src="src" alt="" style="width: 100%; height: 100%; object-fit: cover;" />
      </div>
      <div class="sign-box">
        <div class="row-center title-box">
          <div class="title">{{ text }}</div>
          <n-tooltip placement="right-end" keep-alive-on-hover="true" v-if="data.isLogin == 1" :show-arrow="false"
            :style="{
              background: store.theme == 'default' ? '#161A21' : '#409EFF',
            }">
            <template #trigger>
              <span class="iconfont icon-shuaxin" @click="getRandom"></span>
            </template>
            不喜欢？换一张
          </n-tooltip>
        </div>

        <template v-if="data.isLogin === 1">
          <div class="form-group">
            <input type="text" class="form-control form-control-lg" placeholder="邮箱账户" v-model="data.form.email"
              ref="userCode" @keydown.enter="toLogin" />
          </div>
          <div class="form-group">
            <input type="password" class="form-control form-control-lg" placeholder="用户密码" v-model="data.form.password"
              @keydown.enter="toLogin" />
          </div>
          <n-button class="login-btn" :color="store.theme == 'default' ? '#161A21' : '#409EFF'"
            @click="toLogin">登录</n-button>
        </template>
        <template v-else>
          <div class="form-group">
            <input type="text" class="form-control form-control-lg" placeholder="QQ邮箱" v-model="data.registerForm.email"
              ref="emailInput" />
          </div>
          <div class="form-group">
            <input type="text" class="form-control form-control-lg" placeholder="用户昵称" v-model="data.registerForm.name"
              ref="emailInput" />
          </div>
          <n-button class="login-btn" :color="store.theme == 'default' ? '#161A21' : '#409EFF'" @click="openModel"
            :loading="data.loading">{{ data.loading ? "获取数据中" : "注册" }}</n-button>
        </template>
        <div class="sign-bottom">
          <div v-if="data.isLogin == 1" @click="tiggerSelect">立即注册</div>
          <div v-else @click="tiggerSelect">立即登陆</div>
        </div>
      </div>
    </main>
    <n-modal v-model:show="data.showModal">
      <div v-if="data.step == 1" class="tip-content">
        <div class="popup-header">
          <span class="iconfont icon-youxiang"></span>
        </div>
        <div class="form-group">
          <input type="text" class="form-code form-control-lg" placeholder="" :maxlength="6"
            v-model="data.verificationCode" />
        </div>
        <div class="tip-bottom">
          <n-button v-if="!data.sendVerificationCodeState" class="btn"
            :color="store.theme == 'default' ? '#161A21' : '#409EFF'" @click="toSendEmailCode">获取验证码</n-button>
          <n-button v-else class="btn" :color="store.theme == 'default' ? '#161A21' : '#409EFF'"
            :disabled="data.sendVerificationCodeState">已发送({{ data.countdown }})</n-button>
          <n-button class="btn" :disabled="!(
            data.verificationCode.length == 6 &&
            data.hasSendVerificationCode
          )
            " :color="store.theme == 'default' ? '#161A21' : '#409EFF'" @click="toCheckSendEmailCode">下一步</n-button>
        </div>
      </div>
      <div v-else class="tip-content" style="height: 450px">
        <div class="popup-header">
          <span class="iconfont icon-dunpai"></span>
        </div>
        <div class="form-group">
          <input type="text" class="form-control form-control-lg" placeholder="用户姓名" v-model="data.registerForm.name" />
        </div>
        <div class="form-group">
          <input type="password" class="form-control form-control-lg" placeholder="密码"
            v-model="data.registerForm.password" ref="passwordInput" />
        </div>
        <div class="form-group">
          <input type="password" class="form-control form-control-lg" placeholder="确认密码"
            v-model="data.registerForm.surePassword" />
        </div>
        <div class="tip-bottom">
          <n-button class="btn" :color="store.theme == 'default' ? '#161A21' : '#409EFF'" @click="toRegister">确认</n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>
<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, nextTick, ref } from 'vue';
import { useMainStore } from '../store/index';
import { useMessage } from 'naive-ui';
import img from '../assets/img/bk4.jpg'
import { InitData } from '../page/InitData';
import { md5 } from 'js-md5';
import { login, register ,SendEmailCode,CheckSendEmailCode} from "../api/user"
const messageBox = useMessage()
const store:any = useMainStore()
const { proxy }: any = getCurrentInstance()
let src=ref(img)
onMounted(() => {
  proxy.$refs.userCode.focus()
  setTimeout(() => {
    data.showPopover = true
  }, 4000)
  data.gifIndex = randomNum(1, 4);
})
let data = reactive(new InitData());
let text = ref("欢迎登录")
function initChangeStage(state: number) {
  data.isLogin = state;
  data.step = 1;
  data.verificationCode = "";
  data.sendVerificationCodeState = false;
  data.hasSendVerificationCode = false;
  data.registerForm.email = "";
  data.registerForm.name = "";
  data.registerForm.password = "";
  data.registerForm.surePassword = "";
  data.form.email = "";
  data.form.password = "";
  data.countdown = 60;
  data.timer = null;
}
function toLogin() {
  if (!(data.form.email && data.form.password)) {
    messageBox.warning("账号或密码不能为空");
    return;
  }
  else {
    login(data.form).then((res: any) => {
      if (res?.code === 200) {
        console.log(res?.data)
        store.initSetInfo(res?.data);
        messageBox.success("登录成功");
        proxy.$router.push("/chat");
      }
      else {
        if (messageBox != undefined) {
          messageBox.error(res?.message);
        }
      }
    }
    )
  }
}
async function openModel() {
  try {
    if (!data.registerForm.email.includes("@qq.com")) {
      messageBox.warning("请输入正确的QQ邮箱");
      return;
    }
    if (!data.registerForm.name) {
      messageBox.warning("请输入昵称");
      return;
    }
    if (data.registerForm.name.length < 2) {
      messageBox.warning("昵称不得小于两位");
      return;
    }
    let md5_text = md5(data.registerForm.email);
    console.log(md5_text)
    data.registerForm.avatar = `https://cravatar.cn/avatar/${md5_text}?d=robohash`;
    data.showModal = true;
  } catch (err: any) {
    messageBox.error(err);
  }
}
function toRegister() {
  if (!data.registerForm.name) {
    messageBox.warning("用户名不能为空")
    return
  }
  if (!data.registerForm.password) {
    messageBox.warning("密码不能为空")
  }
  if (data.registerForm.password !== data.registerForm.surePassword) {
    messageBox.warning("两次密码不一致")
  }
  register(data.registerForm).then((res: any) => {
    if (res?.code === 200) {
        messageBox.success("注册成功");
        data.showModal = false;
        initChangeStage(1);
    }
    else{
      messageBox.error(res?.message);
    }
  })
}
function toSendEmailCode() {
  if (!data.registerForm.email) {
    messageBox.warning("邮箱不能为空");
    return;
  }
  let query = {
    email: data.registerForm.email,
    timestamp: data.timestamp,
  };
  SendEmailCode(query).then((res: any) => {
    if (res?.code == 200) {
      messageBox.success(res?.message);
      data.sendVerificationCodeState = true;
      data.hasSendVerificationCode = true;
      data.timer = setInterval(() => {
        if (data.countdown < 1) {
          if (data.timer != null) {
            clearInterval(data.timer);
            data.timer = null;
          }
          data.countdown = 60;
          data.hasSendVerificationCode = false;
        } else {
          data.countdown--;
        }
      }, 1000);
    } else {
      messageBox.error(res?.message);
    }
  });
  
}
function toCheckSendEmailCode() {
  let query = {
    verificationCode: data.verificationCode,
    timestamp: data.timestamp,
  };
  CheckSendEmailCode(query).then((res: any) => {
    if (res?.code == 200) {
      if (data.timer != null && data.timer != undefined) {
        clearInterval(data.timer);
        data.timer = null;
      }
      data.step = 2;
      data.countdown = 60;
      data.sendVerificationCodeState = false;
      proxy.$nextTick(() => {
        proxy.$refs.passwordInput.focus();
      });
    } else {
      messageBox.error(res?.message);
    }
  });
}
function tiggerSelect() {
  if (data.isLogin == 1) {
    initChangeStage(0);
    text.value = "注册"
    proxy.$nextTick(() => {
      proxy.$refs.emailInput.focus();
    });
  } else {
    initChangeStage(1);
    text.value = "欢迎登录"
    proxy.$nextTick(() => {
      proxy.$refs.userCode.focus();
    });
  }
}
function getRandom() {
  data.gifIndex = randomNum(1, 4);
 newFunction(data.gifIndex);
}
function newFunction(data:number) {
  src.value = new URL(`../assets/img/bk${data}.jpg`, import.meta.url).href;
}

function randomNum(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
</script>
<style scoped lang="less">
@primary-bgcolor: #f0f2f5; // 背景颜色
@primary-bg2color: #ffffff; // 次级背景颜色
@primary-color: #409EFF; // 主要颜色
@input-border-color: #e0e0e0; // 输入框边框颜色
@input-border-txcolor: #333333; // 输入框文字颜色
@primary-txcolor: #333333; // 主要文字颜色
@boxshow-color: #d1d1d1; // 盒子阴影颜色
@boxshow-color2: #ffffff; // 盒子阴影颜色2

.tip-content {
  background-color: @primary-color;
  border: 1px solid @primary-bg2color;
  box-shadow: none;
  width: 400px;
  height: 350px;
  padding: 20px;
  border-radius: 10px;

  .popup-header {
    width: 100%;
    text-align: center;

    .icon-youxiang {
      font-size: 80px;
    }

    .icon-dunpai {
      font-size: 50px;
    }
  }

  .tip-bottom {
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;

    .btn {
      width: 40%;
      height: 50px;
    }
  }
}

.form-group {
  margin-bottom: 40px;
}

.form-code {
  border: 1px solid @primary-bg2color;
  background-color: @primary-bg2color;
  color: @input-border-txcolor;
  box-shadow: none;
  border-radius: 5px;
  font-weight: 400;
  display: block;
  width: 60%;
  margin: 0 auto;
  border-bottom: 1px solid #fff;
  text-align: center;
}

.form-control {
  border: 1px solid @input-border-color;
  background-color: @input-border-color;
  color: @input-border-txcolor;
  -webkit-box-shadow: none;
  box-shadow: none;
  border-radius: 5px;
  font-weight: 400;
  display: block;
  width: 80%;
  outline: none;
  margin: 0 auto;
}

.form-control-lg {
  font-size: 18px;
  line-height: 1.5;
  padding: 5px 8px;
  height: 50px;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: @primary-bgcolor;
  display: flex;
  align-items: center;
  justify-content: center;

  @media screen and (max-width: 768px) {
    height: auto;
    min-height: 100vh;
    // padding: 20px;
  }

  .sign-main {
    width: 960px;
    height: 500px;
    display: flex;
    padding: 10px;
    background: @primary-bg2color;
    box-shadow: inset 9px 9px 18px @boxshow-color,
      inset -9px -9px 18px @boxshow-color2;
    border-radius: 20px;

    @media screen and (max-width: 768px) {
      flex-direction: column;
      width: 100%;
      height: 100vh;
      border-radius: 0;
    }

    .image-box {
      width: 50%;
      height: 100%;
      border-radius: 20px;
      overflow: hidden;

      @media screen and (max-width: 768px) {
        width: 100%;
        height: 200px;
        border-radius: 0;
      }
    }

    .sign-box {
      width: 50%;
      height: 100%;
      padding: 14px;

      @media screen and (max-width: 768px) {
        width: 100%;
        padding: 20px;
      }

      .sign-bottom {
        margin-top: 20px;
        height: 50px;
        color: black;
        background-color: wheat;
        display: flex;
        width: 80%;
        margin-left: 10%;
        align-items: center;
        justify-content: center;

        div {
          cursor: pointer;
        }
      }

      .title-box {
        margin-bottom: 50px;
        height: 60px;

        .title {
          text-align: center;
          font-weight: 900;
          color: @primary-txcolor;
          font-size: 28px;
          margin-right: 20px;
        }

        .icon-shuaxin {
          font-size: 35px;
          cursor: pointer;
          color: @primary-color;
        }
      }

      .login-btn {
        width: 80%;
        height: 50px;
      }
    }
  }
}
</style>